package com.ruoyi.youtian.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.AutoSetDefaultParams;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.youtian.domain.Template;
import com.ruoyi.youtian.domain.vo.TemplatePointBO;
import com.ruoyi.youtian.domain.vo.TemplateVO;
import com.ruoyi.youtian.mapper.TemplateMapper;
import com.ruoyi.youtian.service.ITemplateService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 模板Controller
 *
 * @author ruoyi
 * @date 2022-09-07
 */
@Controller
@RequestMapping("/youtian/template")
public class TemplateController extends BaseController
{
    @Autowired
    private ITemplateService templateService;
    @Autowired
    private TemplateMapper templateMapper;

    private String prefix = "youtian/template";

    @GetMapping()
    public String workspaceCategory()
    {
        return prefix + "/template";
    }


    @GetMapping("/edit/index")
    public String templateEdit()
    {
        return prefix + "/edit/index";
    }


    /**
     * 查询模板列表
     */
    //  @PreAuthorize("@ss.hasPermi('system:template:list')")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list( Template template)
    {
        String loginName = getLoginName();
        startPage();
        List<Template> list = templateService.selectTemplateList(template);
        list.stream().forEach(t->{
            t.setOwner(judgeOwner(t.getCreateBy(), loginName));
        });
        return getDataTable(list);
    }

    private boolean judgeOwner(String createBy, String loginName){
        return loginName.equals(createBy);
    }


    /**
     * 导出模板列表
     */
//    @PreAuthorize("@ss.hasPermi('system:template:export')")
    @Log(title = "模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Template template)
    {
        List<Template> list = templateService.selectTemplateList(template);
        ExcelUtil<Template> util = new ExcelUtil<Template>(Template.class);
        util.exportExcel(response, list, "模板数据");
    }

    /**
     * 获取模板详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:template:query')")
    @GetMapping(value = "/getByTemplateId")
    @ResponseBody
    public AjaxResult getInfo(Long templateId)
    {
        return AjaxResult.success(templateService.selectTemplateByTemplateId(templateId));
    }

    /**
     * 新增模板详情
     *
     */
//    @PreAuthorize("@ss.hasPermi('system:template:add')")
    @Log(title = "模板", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/saveDetail")
    @ResponseBody
    @AutoSetDefaultParams
    public AjaxResult add(@RequestBody TemplateVO templateVO) {

        templateVO.setDeptId(getSysUser().getDeptId());
        templateVO.setDeptName(getSysUser().getDept().getDeptName());
        long l = templateService.insertTemplate(templateVO);

        return Objects.equals(0,l)? error():success();
    }


    @Log(title = "模板", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/saveTemplate")
    @ResponseBody
    @AutoSetDefaultParams
    public AjaxResult saveTemplate(@RequestBody Template template) {
        template.setCreateBy(getLoginName());
        template.setDeptId(getSysUser().getDeptId());
        template.setDeptName(getSysUser().getDept().getDeptName());
        int result = templateMapper.insertTemplate(template);
        return Objects.equals(0,result)? error():success();
    }


    @RequestMapping(value = "/copyTemplate")
    @ResponseBody
    @AutoSetDefaultParams
    public AjaxResult copyTemplate(@RequestBody Template template){

        template.setDeptId(getSysUser().getDeptId());
        template.setDeptName(getSysUser().getDept().getDeptName());
        int result = templateService.copyTemplate(template);

        return Objects.equals(0,result)? error():success();
    }


    /**
     * 修改模板
     */
//    @PreAuthorize("@ss.hasPermi('system:template:edit')")
    @Log(title = "模板", businessType = BusinessType.UPDATE)
    @RequestMapping("/update")
    @ResponseBody
    @AutoSetDefaultParams
    public AjaxResult edit(@RequestBody TemplateVO templateVO) {

        return toAjax(templateService.updateTemplate(templateVO));
    }


    @RequestMapping("/updateTemplate")
    @ResponseBody
    @AutoSetDefaultParams
    public AjaxResult edit(@RequestBody Template template) {

        return toAjax(templateMapper.updateTemplate(template));
    }



    /**
     * 删除模板
     */
//    @PreAuthorize("@ss.hasPermi('system:template:remove')")
    @Log(title = "模板", businessType = BusinessType.DELETE)
	@RequestMapping("/delete/{templateIds}")
    @ResponseBody
    public AjaxResult remove(@PathVariable Long[] templateIds)
    {
        return toAjax(templateService.deleteTemplateByTemplateIds(templateIds));
    }


    /**
     * 模型设计 通过场景id查询模型列表
     * @param templatePointBO
     * @return
     */
    @RequestMapping("/selectTemplatePoint")
    @ResponseBody
    public AjaxResult selectTemplatePoint(@RequestBody TemplatePointBO templatePointBO){

        List<TemplatePointBO> sourceList = templateMapper.templatePointSourceList(templatePointBO);
        List<TemplatePointBO> targetList = templateMapper.templatePointTargetList(templatePointBO);
        if (CollectionUtils.isEmpty(sourceList) && CollectionUtils.isEmpty(targetList)) {
            return AjaxResult.success();
        }
        sourceList.addAll(targetList);
        Map<Long, List<TemplatePointBO>> collect = sourceList.stream().collect(Collectors.groupingBy(TemplatePointBO::getTemplateId));
        List<Map<String,Object>> resultList=new ArrayList<>();

        collect.keySet().forEach(c->{
            Map<String,Object> map=new HashMap<>();
            map.put("templateId",c);
            map.put("templateName",collect.get(c).get(0).getTemplateName());
            map.put("pointList",collect.get(c));
            resultList.add(map);
        });

        return AjaxResult.success(resultList);
    }


    @RequestMapping("/shareTemplate")
    @ResponseBody
    @AutoSetDefaultParams
    public AjaxResult shareTemplate(@RequestBody Template template) {
        template.setUpdateBy(getLoginName());
        Template t = templateService.getById(template.getTemplateId());
        if((getLoginName()).equals(t.getCreateBy())){
            int i = templateService.shareTemplate(template);
            return  toAjax(i);
        }
        return toAjax(0);
    }
}
